package com.android.often.util.animation;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;
import android.widget.RemoteViews.RemoteView;

@RemoteView
public class AnimatedImageView extends ImageView {
	AnimationDrawable mAnim;
	boolean mAttached;
	
	private String TAG = getClass().getSimpleName();
	
	

	public AnimatedImageView(Context context) {
		super(context);
		
	}

	@Override
	protected void onFinishInflate() {
		// TODO Auto-generated method stub
		super.onFinishInflate();
		
		Log.v(TAG, "onFinishInflate");
		
	}
	
	public AnimatedImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	private void updateAnim() {
		final Drawable drawable = getDrawable();
		if (mAttached && mAnim != null) {
			mAnim.stop();
		}
		if (drawable instanceof AnimationDrawable) {
			mAnim = (AnimationDrawable) drawable;
			if (mAttached) {
				mAnim.start();
			}
		} else {
			mAnim = null;
		}
	}

	 void startAnim() {
		if (mAnim != null && !mAnim.isRunning()) {
			mAnim.start();
		}
	}

	public void stopAnim() {
		if (mAnim != null && mAnim.isRunning()) {
			mAnim.stop();
		}
	}

	@Override
	public void setImageDrawable(Drawable drawable) {
		super.setImageDrawable(drawable);
		updateAnim();
		Log.v(TAG, "setImageDrawable");
	}

	@Override
	public void setImageResource(int resid) {
		super.setImageResource(resid);
		updateAnim();
		Log.v(TAG, "setImageResource");
	}

	@Override
	public void onAttachedToWindow() {
		super.onAttachedToWindow();
		if (mAnim != null) {
			mAnim.start();
		}
		mAttached = true;
		Log.v(TAG, "onAttachedToWindow");
	}

	@Override
	public void onWindowFocusChanged(boolean hasWindowFocus) {
		if (hasWindowFocus && mAnim != null) {
			mAnim.start();
			mAttached = true;
		}else if(!hasWindowFocus && mAnim != null){
			mAnim.stop();
			mAttached = false;
		}
		super.onWindowFocusChanged(hasWindowFocus);
		Log.v(TAG, "onWindowFocusChanged");
	}

	@Override
	public void onDetachedFromWindow() {
		super.onDetachedFromWindow();
		if (mAnim != null) {
			mAnim.stop();
		}
		mAttached = false;
		Log.v(TAG, "onDetachedFromWindow");
	}
}
